package com.stellar.circle.domain.sPostTag.impl;

import com.stellar.circle.basic.entity.SPostTag;
import com.stellar.circle.basic.entity.SPostTagMapping;
import com.stellar.circle.basic.service.SPostTagMappingService;
import com.stellar.circle.basic.service.SPostTagService;
import com.stellar.circle.constants.CircleConstants;
import com.stellar.circle.controller.admin.sPostTag.vo.*;
import com.stellar.circle.convert.SPostTagConvert;
import com.stellar.circle.domain.sPostTag.SPostTagDomainService;

import com.stellar.web.core.bean.PageResult;
import com.stellar.web.core.enums.IsDeletedFlagEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 话题表领域服务实现
 *
 * @author Jqchan
 * @version 1.0
 * @date 2025-05-17 19:30:35
 */
@Service
public class SPostTagDomainServiceImpl implements SPostTagDomainService {

    @Resource
    private SPostTagService sPostTagService;

    @Resource
    private SPostTagMappingService sPostTagMappingService;

    @Override
    public PageResult<SPostTagResponseVO> page(SPostTagRequestPageVO requestPageVO) {
        PageResult<SPostTagResponseVO> pageResult = new PageResult<>();
        SPostTag queryEntity = SPostTagConvert.INSTANCE.convert(requestPageVO);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());

        List<SPostTag> entities = sPostTagService.page(queryEntity,
                requestPageVO.getStart(), requestPageVO.getPageSize());

        if (entities.isEmpty()) {
            return pageResult;
        }

        Long count = sPostTagService.count(queryEntity);
        List<SPostTagResponseVO> vos = SPostTagConvert.INSTANCE.convertEntityToRespList(entities);

        pageResult.setResult(vos);
        pageResult.setTotal(count.intValue());
        return pageResult;
    }

    @Override
    public Boolean update(SPostTagRequestVO requestVO) {
        SPostTag entity = SPostTagConvert.INSTANCE.convert(requestVO);
        return sPostTagService.update(entity) != 0;
    }

    @Override
    public Boolean delete(Long id) {
        SPostTag entity = new SPostTag();
        entity.setId(id);
        entity.setIsDeleted(IsDeletedFlagEnum.DELETED.getVal());
        return sPostTagService.update(entity) != 0;
    }

    @Override
    public Boolean insert(SPostTagRequestVO requestVO) {
        SPostTag entity = SPostTagConvert.INSTANCE.convert(requestVO);
        entity.setUsageCount(0);
        return sPostTagService.insert(entity) != 0;
    }

    @Override
    public SPostTagResponseVO get(Long id) {
        SPostTag entity = sPostTagService.queryById(id);
        return SPostTagConvert.INSTANCE.convert(entity);
    }

    @Override
    public PageResult<SPostTagResponseVO> pageForMiniApp(SPostTagRequestPageVO requestPageVO) {
        // 参数校验
        if (requestPageVO.getIsCurrentSchool() == CircleConstants.SCHOOL_TOPIC && requestPageVO.getSchoolId() == null) {
            throw new IllegalArgumentException("schoolId must not be null for school topic");
        }

        PageResult<SPostTagResponseVO> pageResult = new PageResult<>();
        List<SPostTagResponseVO> vos = Collections.emptyList();
        Long total = 0L;

        // 构建基础查询实体
        SPostTag queryEntity = SPostTagConvert.INSTANCE.convert(requestPageVO);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());

        if (CircleConstants.GLOBAL_TOPIC == requestPageVO.getIsCurrentSchool()) {
            // 处理全局话题
            List<SPostTag> tagPage = sPostTagService.page(queryEntity,
                    requestPageVO.getStart(), requestPageVO.getPageSize());
            vos = convertToVO(tagPage);
            total = sPostTagService.count(queryEntity);
        } else if (CircleConstants.SCHOOL_TOPIC == requestPageVO.getIsCurrentSchool()) {
            // 处理学校话题
            List<SPostTagMapping> mappingPage = sPostTagMappingService.pageBySchoolId(
                    requestPageVO.getSchoolId(),
                    requestPageVO.getStart(),
                    requestPageVO.getPageSize()
            );

            if (!mappingPage.isEmpty()) {
                List<Long> tagIds = mappingPage.stream()
                        .map(SPostTagMapping::getTagId)
                        .collect(Collectors.toList());

                // 批量查询并保持顺序
                Map<Long, SPostTag> tagMap = sPostTagService.queryByIds(tagIds).stream()
                        .filter(tag -> IsDeletedFlagEnum.UN_DELETED.getVal().equals(tag.getIsDeleted()))
                        .collect(Collectors.toMap(SPostTag::getId, Function.identity()));

                List<SPostTag> orderedTags = tagIds.stream()
                        .map(tagMap::get)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                vos = convertToVO(orderedTags);
            }
            total = sPostTagMappingService.countBySchool(requestPageVO.getSchoolId());
        }

        pageResult.setResult(vos);
        pageResult.setTotal(total.intValue());
        return pageResult;
    }

    @Override
    public PostTagOverviewVO getTagOverview() {
        PostTagOverviewVO vo = new PostTagOverviewVO();

        // 获取基础统计
        PostTagOverviewVO stats = sPostTagService.selectTagStats();
        vo.setGlobalTags(stats.getGlobalTags());
        vo.setTotalTags(stats.getTotalTags());
        vo.setPinnedTags(stats.getPinnedTags());
        vo.setTotalUsage(stats.getTotalUsage());

        // 获取类型分布
        PostTagOverviewVO rawDistribution = sPostTagService.selectTypeDistribution();

        vo.setGlobalCount(rawDistribution.getGlobalCount());
        vo.setSchoolCount(rawDistribution.getSchoolCount());

        // 获取使用趋势
        vo.setUsageTrends(sPostTagService.selectRecentUsageTrend());

        return vo;
    }

    @Override
    public List<HotTopicVO> getHotTopics() {
        return sPostTagService.selectHotTopics();
    }

    private List<SPostTagResponseVO> convertToVO(List<SPostTag> tags) {
        return tags.isEmpty() ? Collections.emptyList()
                : SPostTagConvert.INSTANCE.convertEntityToRespList(tags);
    }
//    public PageResult<SPostTagResponseVO> pageForMiniApp(SPostTagRequestPageVO requestPageVO) {
//        PageResult<SPostTagResponseVO> pageResult = new PageResult<>();
//
//        SPostTag queryEntity = SPostTagConvert.INSTANCE.convert(requestPageVO);
//        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
//
//        List<SPostTagResponseVO> vos = null;
//        // 判断是否全局话题
//        if (PostConstants.GLOBAL_TOPIC == requestPageVO.getIsCurrentSchool()) {
//            // 获取全部话题
//            List<SPostTag> entities = sPostTagService.page(queryEntity,
//                    requestPageVO.getStart(), requestPageVO.getPageSize());
//
//            if (entities.isEmpty()) {
//                return pageResult;
//            }
//
//            vos = SPostTagConvert.INSTANCE.convertEntityToRespList(entities);
//
//        } else if (PostConstants.SCHOOL_TOPIC == requestPageVO.getIsCurrentSchool()) {
//            // 获取当前学校Id
//            Long schoolId = requestPageVO.getSchoolId();
//            SPostTagMapping sPostTagMapping = new SPostTagMapping();
//            sPostTagMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
//            sPostTagMapping.setSchoolId(schoolId);
//            List<SPostTagMapping> sPostTagMappings = sPostTagMappingService.queryAllByCondition(sPostTagMapping);
//            List<Long> tagIds = sPostTagMappings.stream().map(SPostTagMapping::getTagId).collect(Collectors.toList());
//            List<SPostTag> entities = sPostTagService.queryByIds(tagIds);
//            vos = SPostTagConvert.INSTANCE.convertEntityToRespList(entities);
//        }
//
//        Long count = sPostTagService.count(queryEntity);
//
//        pageResult.setResult(vos);
//        pageResult.setTotal(count.intValue());
//
//        return pageResult;
//    }
}
